package com.zilue.hfqueue.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ZD on 2017/6/1.
 */
public class ChannelServer {
    private static final int MAX=4;
    private static final ExecutorService executor= Executors.newFixedThreadPool(MAX);
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8091));
        System.out.println("listening port 8091!");
//        while (true){
//            SocketChannel socketChannel = serverSocketChannel.accept();
//        executor.execute(new RequestHandler(channel.accept()));
//        }
        Selector selector = Selector.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            int readChannels = selector.select();
            if (readChannels==0)
                continue;
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if(key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    new Thread(new RequestHandler(channel.accept())).start();
//                    executor.execute(new RequestHandler(channel.accept()));
                } else if (key.isConnectable()) {
                    // a connection was established with a remote server.
                } else if (key.isReadable()) {
                    // a channel is ready for reading
                } else if (key.isWritable()) {
                    // a channel is ready for writing
                }
                iterator.remove();
            }
        }
    }


}
